import 'package:flutter_tts/flutter_tts.dart';
import 'dart:io';

class TTSService {
  static final TTSService _instance = TTSService._internal();
  final FlutterTts _tts = FlutterTts();
  bool _isInitialized = false;
  String _currentText = '';  // 添加当前文本缓存
  Function(String, int)? onWordCallback;  // 修改回调函数类型

  factory TTSService() => _instance;

  TTSService._internal();

  static List<String> splitText(String text) {
    return text
        .split(RegExp(r'[\s,，.]|\n'))  // 添加 \n 作为分隔符
        .where((w) => w.isNotEmpty)
        .map((w) => w.trim())
        .toList();
  }

  Future<void> init() async {
    if (_isInitialized) return;

    try {
      await _tts.setLanguage("en-US");
      await _tts.setSpeechRate(0.3);
      await _tts.setVolume(1.0);
      await _tts.setPitch(1.0);

      // iOS 特定设置
      if (Platform.isIOS) {
        await _tts.setSharedInstance(true);
        await _tts.setIosAudioCategory(
          IosTextToSpeechAudioCategory.ambient,
          [
            IosTextToSpeechAudioCategoryOptions.allowBluetooth,
            IosTextToSpeechAudioCategoryOptions.allowBluetoothA2DP,
            IosTextToSpeechAudioCategoryOptions.mixWithOthers,
          ],
        );
      }

      _tts.setProgressHandler((String text, int start, int end, String word) {
        print('Progress Handler - Word: "$word" at position: $start-$end');
        if (onWordCallback != null) {
          // 使用缓存的文本进行分词
          final words = _currentText
              .split(RegExp(r'(?<=[\s,，.。!?！？、:：])|(?=[\s,，.。!?！？、:：])|\n'))
              .where((w) => w.isNotEmpty)
              .toList();

          // 尝试多种方式找到正确的索引
          int wordIndex = -1;
          
          // 1. 直接匹配
          wordIndex = words.indexOf(word.trim());
          
          // 2. 如果没找到，尝试在 start-end 范围内查找
          if (wordIndex == -1 && Platform.isIOS) {
            final subText = text.substring(0, start).trim();
            wordIndex = subText.split(RegExp(r'\s+')).length - 1;
          }

          if (wordIndex != -1) {
            onWordCallback!(word, wordIndex);
          }
        }
      });
      
      _isInitialized = true;
      print('TTS initialized successfully');
    } catch (e) {
      print('Error initializing TTS: $e');
    }
  }

  void setWordCallback(Function(String, int) callback) {  // 更新方法签名
    onWordCallback = callback;
  }

  // 检查是否已下载离线语音包
  Future<bool> checkOfflineVoice() async {
    if (!_isInitialized) return false;
    
    try {
      final engines = await _tts.getEngines;
      final voices = await _tts.getVoices;
      
      // 检查是否有离线语音包
      bool hasOfflineVoice = engines.any((e) => e.contains('google')) &&
                            voices.any((v) => v.toString().contains('offline'));
      
      return hasOfflineVoice;
    } catch (e) {
      print('Error checking offline voice: $e');
      return false;
    }
  }

  Future<void> speak(String text) async {
    if (!_isInitialized) {
      print('TTS not initialized');
      return;
    }

    try {
      _currentText = text;  // 缓存当前文本
      await _tts.speak(text);
    } catch (e) {
      print('Error speaking: $e');
    }
  }

  Future<void> stop() async {
    if (!_isInitialized) return;
    try {
      await _tts.stop();
      if (onWordCallback != null) {
        onWordCallback!('', -1);
      }
    } catch (e) {
      print('Error stopping TTS: $e');
    }
  }

  void dispose() {
    _tts.stop();
    _isInitialized = false;
  }
} 